package com.oig.sys.auth.service.impl;

import com.oig.common.constants.CommonEnum;
import com.oig.common.exception.BadRequestException;
import com.oig.sys.auth.dao.ITbResourceQltmpDao;
import com.oig.sys.auth.dto.ResourceQltmpDto;
import com.oig.sys.auth.service.ITbResourceQltmpService;
import com.oig.sys.auth.entity.TbResourceQltmp;

import com.oig.sys.auth.vo.ResourceQltmpVo;
import com.oig.sys.security.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wuxl
 */
@Service
@Slf4j
public class TbResourceQltmpServiceImpl implements ITbResourceQltmpService {

	private final ITbResourceQltmpDao tbResourceQltmpDao;

	@Autowired
	public TbResourceQltmpServiceImpl(ITbResourceQltmpDao tbResourceQltmpDao){
		 this.tbResourceQltmpDao = tbResourceQltmpDao;
	}


	@Override
	public List<ResourceQltmpVo> findAllQltmpByResourceId(Integer resourceId, Integer userId) {
		log.debug("resourceId={},userId={}",resourceId,userId);
		return this.tbResourceQltmpDao.findByResourceIdAndUserId(resourceId,userId);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public ResourceQltmpVo saveResourceQltmp(ResourceQltmpDto resourceQltmpDto) {
		TbResourceQltmp resourceQltmp ;
		if (resourceQltmpDto.getId()!=null){
			TbResourceQltmp oldResourceQltmp = this.tbResourceQltmpDao.getTbResourceQltmpById(resourceQltmpDto.getId()) ;
			if (oldResourceQltmp.getUserId()==0){
				resourceQltmp = new TbResourceQltmp();
			} else {
				resourceQltmp = oldResourceQltmp;
			}
		} else {
			resourceQltmp = new TbResourceQltmp();
		}
		BeanUtils.copyProperties(resourceQltmpDto,resourceQltmp);
		resourceQltmp.setUserId(SecurityUtil.getDefineUserMain().getId());
		resourceQltmp.setStatus(CommonEnum.CommonStatusEnum.OK.getCode());
		this.tbResourceQltmpDao.save(resourceQltmp);
		ResourceQltmpVo resourceQltmpVo = new ResourceQltmpVo();
		BeanUtils.copyProperties(resourceQltmp,resourceQltmpVo);
		return resourceQltmpVo;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void delUserQlt(Integer qltId) {
		TbResourceQltmp oldResourceQltmp = this.tbResourceQltmpDao.getTbResourceQltmpById(qltId) ;
		if (oldResourceQltmp==null){
			throw new BadRequestException("数据不存在");
		}
		if (!SecurityUtil.getDefineUserMain().getId().equals(oldResourceQltmp.getUserId())){
			throw new BadRequestException("只能删除自己的");
		}
		this.tbResourceQltmpDao.delete(oldResourceQltmp);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void delUserQltByUserId(Integer userId) {
		List<Integer> idList = this.tbResourceQltmpDao.findAllIdByUserId(userId);
		if (idList!=null && !idList.isEmpty()){
			this.tbResourceQltmpDao.deleteByIdList(idList);
		}
	}
}
